﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Model;
using SqlSugar.Extensions;
using StackExchange.Profiling;
using Utils.Helper;

namespace Api.Filter
{
    public class GlobalExceptionsFilter : IExceptionFilter
    {
        private readonly IWebHostEnvironment _env;
        private readonly ILogger<GlobalExceptionsFilter> _logger;

        public GlobalExceptionsFilter(IWebHostEnvironment env, ILogger<GlobalExceptionsFilter> logger)
        {
            _env = env;
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            var json = new MessageModel<string>();
            json.msg = context.Exception.Message;//错误信息
            json.status = 500;//500异常 

            //if (_env.EnvironmentName.ObjToString().Equals("Development"))
            //{
            //    json.msgDev = context.Exception.StackTrace;//堆栈信息
            //}

            var res = new ContentResult();

            res.Content = JsonHelper.GetJSON<MessageModel<string>>(json);

            context.Result = res;

            MiniProfiler.Current.CustomTiming("Errors：", json.msg);

            _logger.LogError(json.msg + WriteLog(json.msg, context.Exception));

        }

        /// <summary>
        /// 自定义返回格式
        /// </summary>
        /// <param name="throwMsg"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        public string WriteLog(string throwMsg, Exception ex)
        {
            return string.Format("\r\n【自定义错误】：{0} \r\n【异常类型】：{1} \r\n【异常信息】：{2} \r\n【堆栈调用】：{3}", new object[] { throwMsg,
                ex.GetType().Name, ex.Message, ex.StackTrace });
        }


    }

}
